package com.zhihu.matisse.library.provider;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;

public abstract class CursorAdapter extends BaseItemProvider {

    private Context context;
    private ResultSet resultSet;
    private int mRowIDColumn;
    public CursorAdapter(Context context, ResultSet resultSet){
        this.context = context;
        this.resultSet = resultSet;

        mRowIDColumn = resultSet != null ? resultSet.getColumnIndexForName("_id") : -1;
    }

    public ResultSet getResultSet() {
        return resultSet;
    }

    @Override
    public int getCount() {
        if (resultSet != null) {
            return resultSet.getRowCount();
        } else {
            return 0;
        }
    }

    public void swapResultSet(ResultSet newResultSet){
        if (newResultSet == resultSet){
            return;
        }
        resultSet = newResultSet;
        if (newResultSet != null){
            mRowIDColumn = resultSet.getColumnIndexForName("_id");
            notifyDataChanged();
        }else {
            mRowIDColumn = -1;
            notifyDataInvalidated();
        }
    }

    @Override
    public Object getItem(int i) {
        if (resultSet != null) {
            resultSet.goTo(i);
            return resultSet;
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int i) {
        if (resultSet != null) {
            if (resultSet.goTo(i)) {
                return resultSet.getLong(mRowIDColumn);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        if (!resultSet.goTo(i)) {
            throw new IllegalStateException("couldn't move cursor to position " + i);
        }
        Component v;
        if (component == null) {
            v = newView(context, resultSet, componentContainer);
        } else {
            v = component;
        }
        bindView(v, context, resultSet);
        return v;
    }

    public abstract Component newView(Context context, ResultSet cursor, ComponentContainer componentContainer);

    public abstract void bindView(Component view, Context context, ResultSet cursor);
}
